package _4lists.src.stack;


import java.util.LinkedList;

/**
 * @className: zhui
 * @description:
 * @author: myself
 * @date: 2025/7/24 21:09
 * @version: 0.1
 * @since: JDK17
 */

public class zhui {
    public static void main(String[] args) {
        String s = infixToSuffix("a*(b-c)");
        System.out.println(s);//s=abc-*
    }
    //设置不同符号的优先级后遇到相关的符号返回对应的优先级级别
    static int priopity(char c) {
        return switch (c) {
            case '('-> 0;
            case '+','-'-> 1;
            case '*', '/' -> 2;
            default -> throw new IllegalArgumentException("输入的字符不合法");
        };
    }

    //将中缀表达式转换成为后缀表达式
    public static String infixToSuffix(String exp) {
        //首先创建一个栈
        LinkedList<Character> stack = new LinkedList<>();
        //用于字符串的拼接
        StringBuilder sb = new StringBuilder(exp.length());
        for (int i = 0; i < exp.length(); i++) {
            char c = exp.charAt(i);
            switch (c) {
                case '*', '/', '+', '-'->{
                    //当栈为空时，直接加字符就行
                    if (stack.isEmpty()) {
                        stack.push(c);
                    }else {//当新的符号的优先级大的时候，将其入栈
                        if (priopity(c) > priopity(stack.peek())) {
                            stack.push(c);
                        }else {//当栈不为空且当新的符号的优先级小的时候
                            while (!stack.isEmpty()&&priopity(stack.peek()) >=priopity(c)) {
                                sb.append(stack.pop());
                            }
                            stack.push(c);//将较小优先级的符号入栈
                        }
                    }
                }
                case '(' -> {
                    stack.push(c);//直接入栈
                }
                case ')' -> {
                    while (!stack.isEmpty() && stack.peek() != '(') {
                        sb.append(stack.pop());//使其一直出栈
                    }
                    stack.pop();//将（括号出栈
                }
                default -> {
                    sb.append(c);
                }
            }
        }
        while (!stack.isEmpty()) {//将栈中剩余的符号拼接出来
            sb.append(stack.pop());
        }
        return sb.toString();
    }
}
